//
//  SSDKOpenSDK.m
//  SDK_OpenSDK
//
//  Created by 涂俊 on 2018/5/4.
//  Copyright © 2018年 wyht. All rights reserved.
//

#import "SSDKOpenSDK.h"
#import "YCOpenSDK/OpenSDK_Enum.h"
#import "YCSuperSDK/SSDKDelegateWrapper.h"
#import "YCSuperSDK/SSDKDataHelper.h"
#import "YCSuperSDK/SSDKHttpUtil.h"
#import "YCSuperSDK/SSDKDataKeys.h"
#import "YCSuperSDK/SSDKEnum.h"
#import "YCSuperSDK/SSDKErrorInfo.h"
#import "YCSuperSDK/SSDKHttpUtil.h"
#import "YCSuperSDK/SSDKEventManager.h"
#import "YCSuperSDK/SSDKEventKeys.h"
#import "YCSuperSDK/SSDKCheckUtil.h"
#import "YCSuperSDK/SSDKUserManager.h"
#import "YCSuperSDK/SSDKDataKeys.h"
#import "YCSuperSDK/SuperSDKInst.h"
#import "YCSuperSDK/SSDKStatusManager.h"
#import "YCSuperSDK/SSDKStatusManager.h"
#import "LocalData.h"

@implementation SSDKOpenSDK

//openSDK当前UID
NSString *curUID;

-(void) initInfo {
    [SSDKEventManager addObsver:self selector:@selector(initSDK) name:EVENT_INIT object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(login) name:EVENT_LOGIN object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(pay:) name:EVENT_PAY object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(switchAccount) name:EVENT_SWITCHACCOUNT object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(logout) name:EVENT_LOGOUT object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(userCenter) name:@"enterPlatform" object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(submitData:) name:EVENT_SUBMITDATA object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(application_handleOpenURL:) name:EVENT_APPLICATION_HANDLEOPENURL object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(application_openURL_options:) name:EVENT_APPLICATION_OPENURL_OPTIONS object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(application_openURL_sourceApplication_annotation:) name:EVENT_APPLICATION_OPENURL_SOURCEAPPLICATION_ANNOTATION object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(application_didFinishLaunchingWithOptions:) name:EVENT_APPLICATION_DIDFINISHLAUNCHINGWITHOPTIONS object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(applicationDidBecomeActive:) name:EVENT_APPLICATIONDIDBECOMEACTIVE object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(applicationWillEnterForeground:) name:EVENT_APPLICATIONWILLENTERFOREGROUND object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(application_continue_userActivity:) name:EVENT_APPLICATION_CONTINUEUSERACTIVITY object:nil className:@"SSDKOpenSDK"];
    [SSDKEventManager addObsver:self selector:@selector(application_will_terminate:) name:EVENT_APPLICATION_WILL_TERMINATE object:nil className:@"SSDKOpenSDK"];
}

-(void) initSDK {
    [[OpenSDK getInstance] initWithDelegate:self];
}


-(void) login {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[OpenSDK getInstance] login];
    });
}

-(void) logout {
    [[OpenSDK getInstance] logout];
}

-(void) switchAccount {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[OpenSDK getInstance] switchAccount];
    });
}

- (void)userCenter {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[OpenSDK getInstance] userCenter];
    });
}

#pragma -------- OpenSDK初始化回调
-(void) openSDKInitWithCode:(OpenSDK_InitAction)code
                     errStr:(NSString *)errStr {
    switch (code) {
        case OpenSDK_INIT_SUCCESS:
        {
            //初始化成功
            [SSDKUserDelegateWrapper initSuccess];
            NSLog(@"OpenSDK_INIT_SUCCESS");
        }
            break;
        case OpenSDK_INIT_FAIL:
        {
            //初始化失败
            SSDKErrorInfo *error = [[SSDKErrorInfo alloc] init];
            [error setError:@"OpenSDK_INIT_FAIL" withCode:SDK_INIT_FAILED];
            [SSDKUserDelegateWrapper initFail:error];
        }
            break;
            
        default:
            break;
    }
}

#pragma -------- OpenSDK登录回调
-(void) openSDKLoginWithCode:(OpenSDK_UserAction)code
                    userInfo:(OpenSDK_UserInfo *)userInfo errStr:(NSString *)errStr {
    switch (code) {
        case OpenSDK_LOGIN_SUCCESS:
        {
            //用户登录成功
            //获取userInfo
            NSString *token=userInfo.openSDK_token;
            NSString *openID=userInfo.openSDK_openID;
            curUID=openID;
            
            NSString *nickName=userInfo.openSDK_nickName;
            if (nickName != nil && nickName.length > 0 && [self isPureInt:nickName]) {
                // 是手机号登录,记录手机号
                [[SuperSDKInst getInstance] setMobileNumber:nickName];
            } else {
                // 不是手机号登录，手机号设置空
                [[SuperSDKInst getInstance] setMobileNumber:nil];
            }
            
            [SSDKCheckUtil checkUserLoginSuccessState:openID accessToken:token refreshToken:@"" extra:nil];
        }
            break;
        case OpenSDK_LOGIN_FAIL:
        {
            //用户登录失败
            SSDKErrorInfo *error = [[SSDKErrorInfo alloc] initWithError:@"SDK_LOGIN_FAIL" errorNo:SDK_LOGIN_FAILED errorMsg:errStr];
            [SSDKUserDelegateWrapper loginFail:error];
        }
            break;
        case OpenSDK_LOGIN_CANCEL:
        {
            //用户取消登录
            [SSDKUserDelegateWrapper loginCancel];
        }
            break;
        case OpenSDK_LOGOUT_SUCCESS:
        {
            //用户登出成功
            [[SuperSDKInst getInstance] setMobileNumber:nil];
            [SSDKUserDelegateWrapper logoutSuccess];
        }
            break;
            
        default:
            break;
    }
    //为了处理苹果特殊返回两次的情况
    [[SSDKStatusManager getInstance] setPayingFlag:NO];
}

-(void) pay:(NSNotification*) notification {
    if(curUID==nil) {
        SSDKErrorInfo *error = [[SSDKErrorInfo alloc] initWithError:@"SDK_PAY_FAIL" errorNo:SDK_PAY_FAIL errorMsg:@"Please login first!"];
        [SSDKPayDelegateWrapper payFail:error];
        return;
    }
    SSDKPaymentData *paymentData=[[notification object] objectForKey:SSDK_E_PAYINFO];
//    [paymentData.data removeObjectForKey:@"notice_url"];
    [SSDKPayInfoUtil postWithData:paymentData extra:paymentData.extra httpDelegate:^(SSDKBaseResData *resData) {
        SSDKFWPayInfo *payInfo = [[SSDKFWPayInfo alloc] initWithPayInfo:resData];
        SSDKAppPayInfo *appPayInfo = [[SSDKAppPayInfo alloc] initWithFWPayInfo:payInfo];
        
        [LocalData saveCurUser:[payInfo roleId] RoleName:[payInfo roleName] RoleGrade:[payInfo roleGrade] RoleBalance:[payInfo roleBalance] SuperSDKUID:[payInfo superSDKUid] GameUID:[payInfo gameUid] ServerID:[payInfo serverId] AppData:[payInfo appData]];
        
        if ([appPayInfo isOk]) {
            OpenSDK_PayInfo *payInfoToOpenSDK=[[OpenSDK_PayInfo alloc] init];
            [payInfoToOpenSDK setProductID:payInfo.productId];
            [payInfoToOpenSDK setOrderAmount:[NSString stringWithFormat:@"%.2f",payInfo.orderAmount]];
            
            [payInfoToOpenSDK setProductName:payInfo.productName];
            [payInfoToOpenSDK setAppData:payInfo.orderId];
            [payInfoToOpenSDK setUid:curUID];
            //组建支付控件
            [[OpenSDK getInstance] payWithPayInfo:payInfoToOpenSDK];
        } else {
            SSDKErrorInfo *error = [[SSDKErrorInfo alloc] initWithError:@"SDK_PAY_FAIL" errorNo:GET_ORDERID_ERROR errorMsg:[resData error]];
            [SSDKPayDelegateWrapper payFail:error];
        }
    }];
}

#pragma -------- OpenSDK支付回调
-(void) openSDKPayWithCode:(OpenSDK_PayAction)code
                 orderInfo:(OpenSDK_OrderInfo *)orderInfo
                    errStr:(NSString *)errStr {
    switch (code) {
        case OpenSDK_PAY_SUCCESS://支付成功
        case OpenSDK_PAY_WAIT_CHECK://支付待验证
        {
            //支付成功,错单的可能性
            //避免错单的情况,如果没有superSDK的orderID则使superSDK服务器创建一个订单，并主动通知游戏服务器
            if([[orderInfo appData] length]==0) {
                NSMutableDictionary *userInfo=[LocalData getCurUser];
                if(userInfo!=nil) {
                    SSDKAppPayInfo *appPayInfo=[[SSDKAppPayInfo alloc] init];
                    [appPayInfo setSuperSDKUid:[userInfo objectForKey:SLocalSuperSDKUID]];
                    NSMutableDictionary *extraData=[[NSMutableDictionary alloc] init];
                    [extraData setObject:[userInfo objectForKey:SLocalRoleID] forKey:@"role_id"];
                    [extraData setObject:[userInfo objectForKey:SLocalRoleName] forKey:@"role_name"];
                    [extraData setObject:[userInfo objectForKey:SLocalRoleGrade] forKey:@"role_grade"];
                    [extraData setObject:[userInfo objectForKey:SLocalRoleBalance] forKey:@"role_balance"];
                    [extraData setObject:[userInfo objectForKey:SLocalAppData] forKey:@"app_data"];
                    [extraData setObject:[userInfo objectForKey:SLocalGameUID] forKey:@"game_uid"];
                    [extraData setObject:[userInfo objectForKey:SLocalServerID] forKey:@"server_id"];
                    [extraData setObject:[orderInfo product] forKey:@"product_id"];
                    [extraData setObject:[orderInfo productAmount] forKey:@"order_amount"];
                    [extraData setObject:[orderInfo orderID] forKey:@"sdk_order_id"];
                    [SSDKCheckUtil checkPaySuccessState:appPayInfo extraData:extraData];
                } else {
                    //支付失败
                    SSDKErrorInfo *error = [[SSDKErrorInfo alloc] initWithError:@"SuperSDK无法补全订单信息，掉单了" errorNo:SDK_PAY_FAIL errorMsg:errStr];
                    [SSDKPayDelegateWrapper payFail:error];
                }
            } else {
                SSDKAppPayInfo *appPayInfo=[[SSDKAppPayInfo alloc] init];
                [appPayInfo setOrderId:[orderInfo appData]];
                [SSDKCheckUtil checkPaySuccessState:appPayInfo extraOrderID:[orderInfo orderID]];
            }
        }
            break;
        case OpenSDK_PAY_FAIL:
        {
            //支付失败
            SSDKErrorInfo *error = [[SSDKErrorInfo alloc] initWithError:@"SDK_PAY_FAIL" errorNo:SDK_PAY_FAIL errorMsg:errStr];
            [SSDKPayDelegateWrapper payFail:error];
        }
            break;
        case OpenSDK_PAY_CANCEL:
        {
            //取消支付
            [SSDKPayDelegateWrapper payCancel];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - OpenSDK 主动切换账号
- (void)openSDKSwitchAccountWithMessage:(NSString *)msg {
    SSDKBaseResData *data = [[[[SSDKBaseResData alloc] init] fail] setError:msg ?: @"" withCode:SDK_ACCOUNT_SWITCH_FAIL_WITH_LOGIN_WINDOW];
    [SSDKUserDelegateWrapper accountSwitchFail:data];
}


#pragma mark - OpenSDK 主动退出登录
- (void)openSDKLoginOutWithMessage:(NSString *)msg {
    [SSDKUserDelegateWrapper logoutSuccess];
}

#pragma -------- OpenSDK统计数据回调
-(void) openSDKStatisticsWithTpye:(NSString *) type
                         dataInfo:(NSDictionary *) dataInfo {
    NSLog(@"OpenSDK数据统计type=%@，data=%@",type, dataInfo);
    NSMutableDictionary *statistics = [[NSMutableDictionary alloc] initWithDictionary:dataInfo];
    [statistics setValue:type forKey:@"ext"];
    [SSDKEventManager postNotificationName:@"reportData" object:statistics];
}

// 游戏上报数据
- (void) submitData:(NSNotification *)notification {
    if([[[notification object] objectForKey:SUBMIT_EXT] isEqualToString:SUBMIT_LOGIN_EVENT]) {
        NSDictionary *object = [notification object];
        [[OpenSDK getInstance] enteredGame:object];
    }
}

#pragma -------- OpenSDK对系统回调的处理
-(void) applicationDidBecomeActive:(NSNotification*) notification {
    [OpenSDK applicationDidBecomeActive:[[notification object] objectForKey:SSDK_E_APPLICATION]];
}

-(void) applicationWillEnterForeground:(NSNotification*) notification {
    [OpenSDK applicationWillEnterForeground:[[notification object] objectForKey:SSDK_E_APPLICATION]];
}

-(void) application_didFinishLaunchingWithOptions:(NSNotification*) notification {
    [OpenSDK application:[[notification object] objectForKey:SSDK_E_APPLICATION]
didFinishLaunchingWithOptions:[[notification object] objectForKey:SSDK_E_DIDFINISHLAUNCHWITHOPTIONS]];
}

-(void) application_handleOpenURL:(NSNotification*) notification {
    [OpenSDK application:[[notification object] objectForKey:SSDK_E_APPLICATION]
           handleOpenURL:[[notification object] objectForKey:SSDK_E_OPENURL]];
}

-(void) application_openURL_sourceApplication_annotation:(NSNotification*) notification {
    [OpenSDK application:[[notification object] objectForKey:SSDK_E_APPLICATION]
                 openURL:[[notification object] objectForKey:SSDK_E_OPENURL]
       sourceApplication:[[notification object] objectForKey:SSDK_E_SOURCEAPPLICATION]
              annotation:[[notification object] objectForKey:SSDK_E_ANNOTATION]];
}

-(void) application_openURL_options:(NSNotification*) notification {
    [OpenSDK application:[[notification object] objectForKey:SSDK_E_APPLICATION]
                 openURL:[[notification object] objectForKey:SSDK_E_OPENURL]
                 options:[[notification object] objectForKey:SSDK_E_OPTIONS]];
}

-(void) application_continue_userActivity:(NSNotification*) notification {
    [OpenSDK application:[[notification object] objectForKey:SSDK_E_APPLICATION]
    continueUserActivity:[[notification object] objectForKey:SSDK_E_USERACTIVITY]];
}

- (void) application_will_terminate:(NSNotification *) notification {
    [OpenSDK applicationWillTerminate:[[notification object] objectForKey:SSDK_E_APPLICATION]];
}

//判断是否是纯数字
- (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

@end
